import mongoose from "mongoose";
import Logger from "../common/logger";

import {IBackTestTrade } from "../types"

class BackTestKlineModel {
    public readonly  model: mongoose.Model<IBackTestTrade>;
    public readonly logger: Logger;
    constructor(db:mongoose.Connection, col_name:string, schema:mongoose.Schema, logger:Logger) {
        this.model = db.model<IBackTestTrade>(col_name, schema);
        this.logger = logger;
    }
    async getKlineByFilter(filter:object) {
        try{

            let ret = await  this.model.findOne(filter);
            return ret;
        }catch(e){
            this.logger.error("getKlines e: ",e);
        }

    }
    async getKlinesByFilter(filter:object,projection:object) {
        try{
            if(projection) {
                let ret = await  this.model.find(filter, projection);
                return ret;
            }else{
                return await this.model.find(filter);
            }

        }catch(e){
            this.logger.error("getKlines e: ",e);
        }

    }
    async insertKline(symbol:string, docData:IBackTestTrade) {
        try{

            console.log('docData: ', docData);
            let oldDoc = await this.model.findOne({symbol:symbol, openTime: docData.openTime});

            console.log('oldDoc: ', oldDoc);
            if(oldDoc === null){
                let doc = new  this.model(docData);
                let newDoc = await doc.save();
                if(newDoc) {
                    this.logger.debug("updateKlines, symbole: ", symbol, " newDoc: ", newDoc);
                }

            }else{
                this.logger.info("updateKlines data double, symoble: ", symbol, "docData: ", docData);
            }

        }catch(e) {
            this.logger.error("insertKline e: ",e);
        }
    }
    async  updateKline(filter:object, updateDoc:IBackTestTrade){
        console.log('updateDoc: ', updateDoc)
        try{
            let res = await this.model.updateOne(filter, updateDoc);
            if(res){
                return true;
            }else{
                return false;
            }
        }catch (e) {
            this.logger.error("updateKline e: ",e);
            return false;
        }
    }
}
export default  BackTestKlineModel;